local ACMH = CreateFrame"Frame"
ACMH.chatmsg = false
ACMH.timer = 0
ACMH:RegisterEvent"PLAYER_LOGIN"

local function Counter(self, elapsed)
	self.timer = self.timer + elapsed
	if self.timer >= ACMHOptions.blocktime then
		self.finish = true
		self:SetScript("OnUpdate", nil)
	end
end
local function ACMH_OnEvent(self, event, ...)
	if event == "PLAYER_LOGIN" then
		if ACMHOptions.blockafter then
			self:SetScript("OnUpdate", Counter)
			self.startedCounter = true
		else
			ACMH.finish = true
		end
	end
end
ACMH:SetScript("OnEvent", ACMH_OnEvent)

local oChatFrame_SystemEventHandler = ChatFrame_SystemEventHandler
ChatFrame_SystemEventHandler = function(...)
	if ACMHOptions.UseHook then
		ACMH.chatmsg = true
	end
	local returnvalue = oChatFrame_SystemEventHandler(...)
	ACMH.chatmsg = false
	return returnvalue
end
local oChatFrame_MessageEventHandler = ChatFrame_MessageEventHandler
ChatFrame_MessageEventHandler = function(...)
	if ACMHOptions.UseHook then
		ACMH.chatmsg = true
	end
	local returnvalue = oChatFrame_MessageEventHandler(...)
	ACMH.chatmsg = false
	return returnvalue
end

local function FindChatMessages(self, event, ...)
	local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11  = ...
	if ACMH.LastChatMSGID ~= arg11 and ACMHOptions.UseFilter then
	--if the id of the last message isn't the same of the id of this message then
		ACMH.LastChatMSGID = arg11
		ACMH.chatmsg = true
	end
	return false, ...
end
for index, value in pairs(ChatTypeGroup) do
	for i, v in pairs(value) do
		ChatFrame_AddMessageEventFilter(v, FindChatMessages)
	end
end
ChatFrame_AddMessageEventFilter("CHAT_MSG_CHANNEL", FindChatMessages)


local function IsABadWord(msg)
	local a = false
	for index, value in pairs(ACMHOptions.badwords) do
		if strfind(strlower(msg), strlower(value)) then
			a = true
		end
	end
	return a
	--a is true if there is a word that may not be shown
end
local function IsAGoodWord(msg)
	local a = false
	for index, value in pairs(ACMHOptions.goodwords) do
		if strfind(strlower(msg), strlower(value)) then
			a = true
		end
	end
	if strfind(strlower(msg), strlower(GUILD_MOTD)) then
		a = true
	end
	return a
	--a is true if there is a word that always have to be shown
end


local CF1AddMessage = ChatFrame1.AddMessage
function ChatFrame1:AddMessage(text, ...)
	if ACMH.chatmsg or IsAGoodWord(text) or (ACMH.finish and not ACMHOptions.blockall and not IsABadWord(text)) or (not ACMH.finish and not ACMHOptions.blockwhileload and not self.startedCounter and not IsABadWord(text)) then
		local returnvalue = CF1AddMessage(ChatFrame1, text, ...)
	elseif ACMHOptions.moveto then
		_G["ChatFrame"..ACMHOptions.moveto]:AddMessage(text, ...)
	end
	ACMH.chatmsg = false
	return returnvalue
end